package com.discovery.common.ret;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author xuebinlu
 * @Date 2018/5/9 16:36
 * @Version 1.0
 * @Description 全局异常处理类
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({NoHandlerFoundException.class})
    public void noHandlerFoundExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        RetResult<Object> result = new RetResult<>(RetCode.NOT_FOUND);
        result.setMsg("接口 [" + request.getRequestURI() + "] 不存在");
        responseResult(response, result);
    }

    @ExceptionHandler(ServiceException.class)
    public void ServiceExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        RetResult<Object> result = new RetResult<>(RetCode.FAIL);
        result.setMsg(e.getMessage()).setData(null);
        responseResult(response, result);
    }

    /**
     * @Title: responseResult
     * @Description: 响应结果
     */
    private void responseResult(HttpServletResponse response, RetResult<Object> result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            ObjectMapper mapper = new ObjectMapper();
            response.getWriter().write(mapper.writeValueAsString(result));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
}
